/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.registration.gui.security;

import it.polimi.registration.business.security.boundary.UserManager;
import it.polimi.registration.business.security.ec.User;
import it.polimi.registration.business.security.jsf.UserController;
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

/**
 *
 * @author miglie
 */
@Named
@RequestScoped
public class RegistrationBean {

    @EJB
    private UserManager um;

    private User user;

    public RegistrationBean() {
    }

    public User getUser() {
        if (user == null) {
            user = new User();
        }
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String register() {
        if(!emailPresent(user)){
            um.save(user);
        }else{
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "Email adress already present."));
            return null;
        }
        return "index?faces-redirect=true";
    }
  
    private boolean emailPresent(User u){
        FacesContext facesContext = FacesContext.getCurrentInstance();
        UserController controller = (UserController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "userController");
        
        List<User> users = controller.getFacade().findAll();
        return users.stream().anyMatch((user1) -> (user1.getUserEmail().equals(u.getUserEmail())));
    }
    
    
}
